package com.moon.app;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.moon.R;
import com.moon.adapter.MainFragmentAdapter;
import com.moon.common.AbstractSherlockFragmentActivity;
import com.moon.constants.MoonConstants;
import com.moon.utils.ImageLoadUtils;
import com.moon.utils.SharedPreferencesUtils;
import com.moon.utils.UpdateCheckerUtils;
import com.moon.utils.UserUtils;
import com.viewpagerindicator.TabPageIndicator;

public class MainActivity extends AbstractSherlockFragmentActivity {
    private View                 mainActionBarView;
    private FragmentPagerAdapter adapter;
    SubMenu                      subMenu;

    private UpdateCheckerUtils   updateChecker;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences shareDate = getSharedPreferences(MoonConstants.SHARED_PREFERENCES_KEY,
                Context.MODE_PRIVATE);

        // 自动检查更新
        String isFirstLoadApp = shareDate.getString(MoonConstants.IS_FIRST_LOAD_APP,
                MoonConstants.TRUE_STRING);
        if (MoonConstants.TRUE_STRING.equals(isFirstLoadApp)) {
            updateChecker = new UpdateCheckerUtils(this);
            updateChecker.startCheckUpdate(true);
            SharedPreferencesUtils.writeLoadInfo(shareDate, MoonConstants.FALSE_STRING, null);
        }

//        if(UserUtils.getHeadImage() != null){
//            subMenu.getItem(0).setIcon(R.drawable.ofm_photo_icon);
//        }
        

        
        initActionBar();
        initView();
    }

    private void initView() {
        adapter = new MainFragmentAdapter(getSupportFragmentManager(), this);
        ViewPager pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);
        TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
        indicator.setViewPager(pager);
    }

    private void initActionBar() {
        // 可以自定义actionbar
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        // 不在actionbar显示logo
        getSupportActionBar().setDisplayShowHomeEnabled(false);

        //		getSupportActionBar().setBackgroundDrawable(
        //				getResources().getDrawable(R.drawable.title_bg));
        mainActionBarView = LayoutInflater.from(this).inflate(R.layout.main_action_bar, null);
        getSupportActionBar().setCustomView(mainActionBarView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        
        //搜索按钮
//		MenuItem search = menu.add("search");
//		search.setIcon(R.drawable.abs__ic_search);
//		search.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		
		//
        SubMenu addMenu = menu.addSubMenu("add item");
        addMenu.add(0, 1, 0, "隽园分享").setIcon(android.R.drawable.ic_input_add);//android自带图标
       // addMenu.add(0, 2, 0, "添加邻居").setIcon(R.drawable.ofm_add_icon);

        MenuItem addItem = addMenu.getItem();
        addItem.setIcon(R.drawable.abs__ic_menu_share_holo_dark);
        addItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        //读用户信息
        SharedPreferences shareDate = getSharedPreferences(MoonConstants.SHARED_PREFERENCES_KEY,
                Context.MODE_PRIVATE);

        subMenu = menu.addSubMenu("action item");
        
        
        subMenu.add(0, 11, 0, shareDate.getString(MoonConstants.USER_NAME, "亲"));
        if (UserUtils.getHeadImage() != null) {
            subMenu.getItem(0).setIcon(UserUtils.getHeadImage());
        }else{
            new BitMapTask().execute(MoonConstants.MOON_DOMAIN_STATIC_HEAD + getUser().getImgUrl());
        }
        

        //subMenu.add(0, 12, 0, "设置").setIcon(R.drawable.ofm_setting_icon);
        subMenu.add(0, 13, 0, "意见反馈").setIcon(R.drawable.ofm_mail_icon);
        subMenu.add(0, 14, 0, "重新登录").setIcon(android.R.drawable.ic_lock_power_off);

        MenuItem menuItem = subMenu.getItem();
        menuItem.setIcon(R.drawable.abs__ic_menu_moreoverflow_holo_dark);
        menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return super.onCreateOptionsMenu(menu);
    }

    //异步获取头像 -- AsyncTask方式
    private class BitMapTask extends AsyncTask<String, String, Bitmap> {

        /*
         * (non-Javadoc)
         * @see android.os.AsyncTask#doInBackground(java.lang.Object[])
         */
        @Override
        protected Bitmap doInBackground(String... params) {
            return ImageLoadUtils.getBitmapFromUrl(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null) {
                UserUtils.setHeadImage(new BitmapDrawable(bitmap));
                //第一个subMenu
                subMenu.getItem(0).setIcon(new BitmapDrawable(bitmap));
            } else {
                subMenu.getItem(0).setIcon(R.drawable.ofm_photo_icon);
            }

        }

    }

    //菜单选择
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case 1:
                Intent intent = new Intent(MainActivity.this, TopicSendActivity.class);
                intent.putExtra(MoonConstants.TOPIC_CATEGORY_ID,
                        MoonConstants.APP_SQUARE_CATEGORY_ID);
                startActivity(intent);
                //startActivity(new Intent(MainActivity.this, SendTopicActivity.class));
                //Toast.makeText(MainActivity.this, "设置", Toast.LENGTH_LONG).show();
                break;
            case 11:
                startActivity(new Intent(MainActivity.this, UserSettingActivity.class));
                //Toast.makeText(MainActivity.this, "设置", Toast.LENGTH_LONG).show();
                break;
            case 13:
                startActivity(new Intent(MainActivity.this, FeedbackActivity.class));
                break;
            case 14:
                SharedPreferences shareDate = getSharedPreferences(
                        MoonConstants.SHARED_PREFERENCES_KEY, Context.MODE_PRIVATE);
                SharedPreferencesUtils.writeUserData(shareDate);
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                break;
            default:
                break;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //Toast.makeText(getApplicationContext(), "再按一次退出", Toast.LENGTH_SHORT).show();

            //退回到桌面
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            //完全退出程序    不退出会有内存问题(程序越来越慢 ,运行内存越来越大)  搞个双击退出
            //System.exit(0);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
